package com.jichangxiu.framework.filter;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.jichangxiu.common.context.JcxContext;
import com.jichangxiu.common.entity.bo.Payload;
import com.jichangxiu.common.utils.JcxContextUtils;
import com.jichangxiu.framework.entity.bo.SecurityToken;
import com.jichangxiu.framework.entity.bo.SecurityUser;
import com.jichangxiu.framework.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@Slf4j
@Component
public class AuthFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.debug("【AuthFilter】当前时间：" + DateUtil.formatDateTime(new Date()));
        log.debug("【AuthFilter】请求地址：" + httpServletRequest.getRequestURI());
        try {
            // 获取用户的权限等信息
            Payload<SecurityUser> payload = SecurityUtils.getPayload(httpServletRequest);
            if (ObjectUtil.isNotEmpty(payload)) {
                log.debug("【AuthFilter】当前的登录用户：" + payload.getUserInfo().getUsername());
                log.debug("【AuthFilter】当前登录用户的【jti】：" + payload.getJti());
                log.debug("【AuthFilter】当前登录用户的【jwt】：" + payload.getJwt());
                // 填充上下文
                fillJcxContext(payload);
                SecurityToken securityToken = new SecurityToken(payload.getUserInfo().getTenantId(),
                        payload.getUserInfo().getUsername(),
                        payload.getUserInfo().getPassword(),
                        payload.getUserInfo().getAuthorities());
                // 设置策略为全局
                SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL);
                SecurityContextHolder.getContext().setAuthentication(securityToken);
            }
        } catch (Exception e) {
            // 这里什么也不错，请求中没有携带 jti 也没事
            log.debug("【AuthFilter】当前没有登录用户");
        } finally {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
        }
    }

    private void fillJcxContext(Payload<SecurityUser> payload) {
        if (ObjectUtil.isNotEmpty(payload)) {
            JcxContextUtils.fillJcxContextEntityByPayload(payload.getJti(), payload.getJwt());
            SecurityUser securityUser = payload.getUserInfo();
            if (ObjectUtil.isNotEmpty(securityUser)) {
                JcxContext.setSecurityUser(securityUser);
                JcxContextUtils.fillJcxContextEntityByTenant(securityUser.getTenantId(), securityUser.getTenantName(), securityUser.getTenantSource());
                JcxContextUtils.fillJcxContextEntityByUser(securityUser.getDeptId(), securityUser.getDeptName(), securityUser.getUserId(), securityUser.getUserCode(), securityUser.getUsername());
                JcxContextUtils.fillJcxContextEntityByAuth(securityUser.getPostRuleList(), securityUser.getRoleRuleList(), securityUser.getPowerRuleList());
            }
        }
    }

}
